package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SETKILL_SCRIPT;
    static {
        SETKILL_SCRIPT = new DefaultRedisScript<>();
        SETKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SETKILL_SCRIPT.setResultType(Long.class);
    }

    // 线程池 ctrl + shift + u 转大写
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    // 在项目启动时提交任务
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    // 订单提交任务 内部类
    private class VoucherOrderHandler implements Runnable{
        String queueName = "stream.orders";
        @Override
        public void run() {
            while(true){
                try{
                    // 1. 获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 1.1 获取失败, 循环等待
                    if (list == null || list.isEmpty()){
                        continue;
                    }
                    // 1.2 获取成功, 解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 1.3  可以下单
                    createVoucherOrder(voucherOrder);
                    // 2. ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                }catch (Exception e){
                    log.error("处理订单异常",e);
                    //处理异常消息
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        String queueName = "stream.orders";
        while (true) {
            try {
                // 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );
                // 2.判断订单信息是否为空
                if (list == null || list.isEmpty()) {
                    // 如果为null，说明没有异常消息，结束循环
                    break;
                }
                // 解析数据
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                // 3.创建订单
                createVoucherOrder(voucherOrder);
                // 4.确认消息 XACK
                stringRedisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
            } catch (Exception e) {
                log.error("处理pendding-list订单异常", e);
                try{
                    Thread.sleep(20);
                }catch(Exception e1){
                    e1.printStackTrace();
                }
            }
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 获取用户
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        // 1.执行lua脚本,获取结果
        Long result = stringRedisTemplate.execute(
                SETKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        assert result != null;
        if (result != 0){
            // 1.2 返回1 库存不足
            // 1.3 返回2 一人一单
            return Result.fail(result == 1 ? "库存不足" : "不能重复下单");
        }
        // 1.1 返回0 succeed
        // TODO 2. 把下单信息放入阻塞队列，异步线程按顺序执行

        // 3. 返回订单id
        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        // 5.1.查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        // 5.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            log.error("用户已经购买过了");
            return ;
        }

        // 6.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0) // where id = ? and stock > 0
                .update();
        if (!success) {
            // 扣减失败
            log.error("库存不足");
            return ;
        }
        save(voucherOrder);
    }

    @Transactional
    public Result createVoucher(Long voucherId) {
        // 3. 下单
        VoucherOrder voucherOrder = new VoucherOrder();
        // other 限制一人一单
        Long userId = UserHolder.getUser().getId();

        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("已达到购买限制");
        }
        // 3.1 修改库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId).gt("stock", 0)
                .update();
        if (!success) {
            //扣减库存
            return Result.fail("不好意思, 卖完了哦！");
        }
        // 3.2 添加订单
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        // 4 返回
        return Result.ok(orderId);
    }

    /*public Result seckillVoucher(Long voucherId) {
        // 1. 查询活动
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        // 2. 判断活动是否有效 (活动时间 库存)
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(voucher.getBeginTime())) {
            return Result.fail("活动还未开启！");
        }
        if (now.isAfter(voucher.getEndTime())) {
            return Result.fail("活动已经结束！");
        }
        if (voucher.getStock() < 1) {
            return Result.fail("不好意思, 卖完了哦! ");
        }
        Long userId = UserHolder.getUser().getId();
        // 3. 一人一单 分布式锁替换
        *//*SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        boolean isLock = simpleRedisLock.tryLock(1200);*//*
        // 3. 分布式锁 redisson
        RLock lock = redissonClient.getLock("order:" + userId);

        boolean isLock = lock.tryLock();

        if (!isLock){
            return Result.fail("一个用户只允许下一单");
        }
        // 4. 执行业务, 释放锁
        try{
            // 通过代理对象调用方法
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            // 这样spring的事务会失效 因为通过this调用
            return proxy.createVoucher(voucherId);
        }finally {
            lock.unlock();
            //simpleRedisLock.unLock();
        }
        // userId.toString().intern() 永远返回 stringTable 里面的对象
        *//*synchronized (userId.toString().intern()){
            // 通过代理对象调用方法
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            // 这样spring的事务会失效 因为通过this调用
            return proxy.createVoucher(voucherId);
        }*//*
    }*/
}
